<template>
  <div class="register">
    <common-header></common-header>
    <div class="regsiterBanner">
      <h3>大众签章开放平台</h3>
    </div>
    <div class="regsiter-box">
      <p class="tip">已有帐号？<router-link tag="span" to="/login">立即登录</router-link></p>
      <el-row :gutter="10">
        <el-col :md="14" :offset="5">
          <el-form :model="register" ref="register" :rules="rules">
            <el-form-item label="" prop="name">
              <el-input type="text" v-model.lazy="register.name" placeholder="名称用于首页显示及信息通知"></el-input>
            </el-form-item>
            <el-form-item label="" prop="phone">
              <el-input v-model.lazy="register.phone" maxlength="11" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="" prop="phoneCode">
              <el-input v-model.lazy="register.phoneCode" placeholder="请输入手机验证码"></el-input>
              <button class="code" :disabled="timePhoneCode.disabled" @click="getPhoneCode">{{ timePhoneCode.txt }}</button>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input show-password v-model.lazy="register.password" placeholder="请输入密码"> </el-input>
            </el-form-item>
            <el-form-item label="" prop="passwordNew">
              <el-input show-password v-model.lazy="register.passwordNew" placeholder="请再次输入密码"></el-input>
              <!-- :type="eyeShow.newpass ? 'text' : 'password'" -->
              <!-- <img
                :src="eyeShow.newpass ? require('@/assets/images/regsiter/eye.png') : require('@/assets/images/regsiter/eye_1.png')"
                alt="Img"
                class="eyeImg"
                @click="eyeShow.newpass = !eyeShow.newpass"
              /> -->
            </el-form-item>
            <el-form-item label="" prop="account">
              <el-input v-model.lazy="register.account" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="" prop="code">
              <el-input type="number" v-model.lazy="register.code" placeholder="请输入动态验证码"></el-input>
              <button class="code" :disabled="timeCode.disabled" @click="getCode">{{ timeCode.txt }}</button>
            </el-form-item>
            <el-form-item style="margin-bottom: 1.2%">
              <el-checkbox v-model="checked" @change="checkClick(checked)"></el-checkbox>
              <span class="check-tip">已阅读并同意<a>《使用协议》</a>及<a>《隐私政策》</a></span>
            </el-form-item>
            <el-form-item label="">
              <el-button type="success" :class="{ desabledactive: desabledBut }" :disabled="desabledBut" align="center" @click="registerForm('register')"
                >同意并注册</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <footer>© 2014-2020 山东国盾网信息科技有限公司版权所有. 保留一切权利. 增值电信业务经营许可证：鲁B2-20130183</footer>
    <!-- 图形验证码的弹框 -->
    <el-dialog title="图形验证码" :visible.sync="dialogImg" :close-on-click-modal="false" :modal-append-to-body="false">
      <img class="httpImg" @click="httpImgClick" :src="httpImg" alt="Img" />
      <el-form :rules="rules">
        <el-form-item label="">
          <el-input v-model="imgCode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImg = false" style="width:100px">取 消</el-button>
        <el-button type="primary" @click="dialogImgClick" style="width:100px;margin-left:30px">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 邮箱图形验证码的弹框 -->
    <el-dialog title="图形验证码" :visible.sync="dialogImgEmail" :close-on-click-modal="false" :modal-append-to-body="false">
      <img class="httpImg" @click="httpImgClick" :src="httpImg" alt="Img" />
      <el-form :rules="rules">
        <el-form-item label="">
          <el-input v-model="imgCodeEmail"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImg = false" style="width:100px">取 消</el-button>
        <el-button type="primary" @click="dialogImgClickEmail" style="width:100px;margin-left:30px">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonHeader from '../../common/commonHeader'
export default {
  name: 'Register',
  components: {
    CommonHeader
  },
  data() {
    // 验证账号
    var validateUser = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入昵称'))
      } else {
        callback()
      }
    }
    // 验证邮箱
    var validateEmail = (rule, value, callback) => {
      const email = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

      if (value === '') {
        callback(new Error('请正确填写邮箱'))
      } else if (!email.test(value)) {
        callback(new Error('请输入有效的邮箱'))
      } else {
        this.timeCode.disabled = false
        callback()
      }
    }
    // 验证密码
    var validatePass = (rule, value, callback) => {
      var str = /([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*/

      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!str.test(value) || value.length < 8) {
        callback(new Error('密码格式最少8位，最多16位，至少含有数字，字母，特殊字符中的两种！'))
      } else {
        callback()
      }
    }
    // 验证再次输入的密码
    var validatePassNew = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.register.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 验证手机号
    var validatePhone = (rule, value, callback) => {
      const phone = /^1[34578]\d{9}$/

      if (value === '') {
        callback(new Error('请正确填写手机号'))
      } else if (!phone.test(value)) {
        callback(new Error('请输入有效的手机号'))
      } else {
        this.timeCode.disabled = false
        callback()
      }
    }
    // 邮箱验证码
    var validateCode = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    // 手机验证码
    var validatePhoneCode = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      identifyCodes: '1234567890',
      identifyCode: '',
      checked: false,
      desabledBut: true,
      register: {
        name: '',
        phone: '',
        phoneCode: '',
        password: '',
        passwordNew: '',
        account: '',
        code: ''
      },
      timeCode: {
        // 邮箱验证码
        txt: '获取验证',
        time: 60,
        disabled: false
      },
      timePhoneCode: {
        // 手机短信验证码
        txt: '获取验证',
        time: 60,
        disabled: false
      },
      eyeShow: {
        pass: false,
        newpass: false
      },
      rules: {
        name: [{ validator: validateUser, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        passwordNew: [{ validator: validatePassNew, trigger: 'blur' }],
        account: [{ validator: validateEmail, trigger: 'blur' }],
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'blur' }],
        phoneCode: [{ validator: validatePhoneCode, trigger: 'blur' }]
      },
      // identifyShow: false, // 验证码状态
      // 图形弹框
      dialogImg: false, // 手机号弹框
      dialogImgEmail: false, // 邮箱弹框
      imgCode: '', // 手机图形码
      imgCodeEmail: '', // 邮箱图形码
      httpImg: ''
    }
  },
  methods: {
    // 注册提交
    registerForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const registers = {
            account: this.register.account,
            phone_code: this.register.phoneCode,
            code: this.register.code,
            name: this.register.name,
            password: this.register.password,
            phone: this.register.phone
          }
          const register = JSON.stringify(registers)
          console.log(register)
          this.http
            .post('/web/login/register', register)
            .then(res => {
              console.log(res)
              const data = res
              if (data.result_code == '0') {
                this.$message({
                  message: '恭喜您，注册成功！',
                  type: 'success'
                })
                this.$router.push('/login')
              } else if (data.result_code == '4003') {
                this.$message({
                  message: data.result_message,
                  type: 'error'
                })
              } else {
                this.$message({
                  message: '注册失败，请重新注册',
                  type: 'error'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    checkClick(er) {
      // 复选框跟按钮联动
      this.desabledBut = !er
    },
    // 邮箱发送验证码
    async getCode() {
      console.log(this.register.account)
      var str = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (this.register.account == '') {
        // 验证码发送消息提示
        // this.$message({
        //   message: '请正确填写邮箱！',
        //   type: 'error'
        // })
        return false
      } else if (!str.test(this.register.account)) {
        // // 验证码发送消息提示
        // this.$message({
        //   message: '请正确填写邮箱！',
        //   type: 'error'
        // })
        return false
      } else {
        // 先获取图形验证码
        this.dialogImgEmail = true
        const num = Math.ceil(Math.random() * 100)
        // 图片流转base64
        const data = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
        console.log(data)
        this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
        // console.log(this.httpImg)
      }
    },
    // 手机发送验证码
    async getPhoneCode() {
      console.log(this.register.phone)
      var str = /^1[3456789]\d{9}$/
      if (this.register.phone == '') {
        // 验证码发送消息提示
        // this.$message({
        //   message: '请正确填写手机号！',
        //   type: 'error'
        // })
        return false
      } else if (!str.test(this.register.phone)) {
        // 验证码发送消息提示
        // this.$message({
        //   message: '请正确填手机号！',
        //   type: 'error'
        // })
        return false
      } else {
        // 先获取图形验证码
        this.dialogImg = true
        const num = Math.ceil(Math.random() * 100)
        // 图片流转base64
        const data = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
        console.log(data)
        this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }
    },
    // 点击刷新图形验证码(用随机数触发)
    async httpImgClick() {
      const num = Math.ceil(Math.random() * 100)
      const data = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
      this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
    },
    // 获取手机验证码
    async dialogImgClick() {
      if (this.imgCode) {
        const codes = {
          account: this.register.phone,
          send_code_type: 6,
          graph_code: this.imgCode
        }
        const codeList = JSON.stringify(codes)
        console.log(codeList)
        const data = await this.http.post('/web/login/send-code', codeList)
        console.log(data)
        if (data.result_code == '0') {
          this.imgCode = '' // 清空验证码
          this.dialogImg = false
          this.codeSuccess()
          // 获取验证码
          this.timePhoneCodes()
        } else {
          this.$message({
            message: data.result_message,
            type: 'error'
          })
        }
        const num = Math.ceil(Math.random() * 100)
        const datas = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
        this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(datas).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }
    },
    // 获取邮箱验证码
    async dialogImgClickEmail() {
      if (this.imgCodeEmail) {
        const codes = {
          account: this.register.account,
          send_code_type: 1,
          graph_code: this.imgCodeEmail
        }
        const codeList = JSON.stringify(codes)
        console.log(codeList)
        const data = await this.http.post('/web/login/send-code', codeList)
        console.log(data)
        if (data.result_code == '0') {
          this.imgCode = '' // 清空验证码
          this.dialogImgEmail = false
          this.codeSuccess()
          // 获取验证码
          this.timeCodes()
        } else {
          this.$message({
            message: data.result_message,
            type: 'error'
          })
        }
        const num = Math.ceil(Math.random() * 100)
        const datas = await this.http.get(`/web/login/get-captcha?${num}`, { responseType: 'arraybuffer' })
        this.httpImg = 'data:image/png;base64,' + btoa(new Uint8Array(datas).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }
    },
    // 手机验证码倒计时
    timePhoneCodes() {
      if (this.timePhoneCode.time > 0) {
        this.timePhoneCode.disabled = true
        this.timePhoneCode.txt = this.timePhoneCode.time + 's'
        this.timePhoneCode.time--
      } else {
        this.timePhoneCode.disabled = false
        this.timePhoneCode.txt = '重新获取'
        this.timePhoneCode.time = 60
        return
      }
      setTimeout(() => {
        this.timePhoneCodes()
      }, 1000)
    },
    // 邮箱验证码倒计时
    timeCodes() {
      if (this.timeCode.time > 0) {
        this.timeCode.disabled = true
        this.timeCode.txt = this.timeCode.time + 's'
        this.timeCode.time--
      } else {
        this.timeCode.disabled = false
        this.timeCode.txt = '重新获取'
        this.timeCode.time = 60
        return
      }
      setTimeout(() => {
        this.timeCodes()
      }, 1000)
    },
    // 验证码发送消息提示
    codeSuccess() {
      this.$message({
        message: '恭喜您，验证码发送成功！',
        type: 'success'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/common.scss';
.desabledactive {
  background: #91dbb4 !important;
}
.identifyCode {
  position: absolute;
  right: 0;
  top: 110%;
  width: 160px;
  z-index: 999;
}
.register {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f0f0f0;
  .regsiterBanner {
    background: url('~@/assets/images/regsiter/regsiter-banner.png') no-repeat;
    background-size: cover;
    width: 100%;
    height: 377px;
    display: flex;
    align-items: center;
    justify-content: center;
    h3 {
      font-size: 50px;
      color: #ffffff;
      letter-spacing: 3px;
      text-align: center;
    }
  }
  .regsiter-box {
    width: 42%;
    margin: -7% auto 0;
    background: #ffffff;
    border-radius: 5px;
    padding: 1.5% 0 0.5%;
    .tip {
      font-size: 14px;
      letter-spacing: 1px;
      margin: 0 3% 5.5% 0;
      display: flex;
      justify-content: flex-end;
      color: #c0c4cc;
      span {
        color: $background;
        cursor: pointer;
      }
    }
    /deep/.el-input__inner {
      padding: 1.2% 0 1.2% 2%;
      font-size: 14px;
    }
    /deep/.el-button {
      width: 100%;
      background: $background;
      font-size: 14px;
      padding: 3%;
      letter-spacing: 1px;
    }
    /deep/.el-form-item {
      margin-bottom: 5%;
    }
    /deep/.el-checkbox__input.is-checked .el-checkbox__inner,
    .el-checkbox__input.is-indeterminate .el-checkbox__inner {
      background: $background;
      border-color: $background;
    }
    /deep/.el-checkbox__input.is-focus .el-checkbox__inner {
      border: 1px solid #dcdfe6;
    }
    .check-tip {
      padding-left: 2%;
      color: #d8d8d8;
      margin-top: 2%;
      display: inline-block;
      a {
        color: $background;
      }
    }
    /deep/.el-form-item__error {
      // top: 22%;
      // right: -20%;
      // left: initial;
    }
    .code {
      position: absolute;
      right: 1%;
      top: 0;
      width: 80px;
      padding: 12px;
      color: #d8d8d8;
      cursor: pointer;
      background: transparent;
      font-size: 14px;
    }
    .eyeImg {
      position: absolute;
      top: 35%;
      right: 5%;
      width: 18px;
      height: 16px;
      z-index: 999;
      cursor: pointer;
    }
  }
  footer {
    // position: fixed;
    // bottom: 2%;
    margin: 100px 0 50px;
    width: 100%;
    font-size: 14px;
    color: #666666;
    letter-spacing: 1px;
    text-align: center;
    margin-top: 80px;
  }
}
// 图形验证码
.httpImg {
  width: 160px;
  margin-bottom: 10px;
  cursor: pointer;
}
/deep/.el-dialog {
  text-align: center;
  width: 30%;
  .el-dialog__body {
    padding: 20px 100px 0;
    .el-input__inner {
      text-align: center;
    }
  }
  .el-button--default:hover {
    background: #fff;
    color: #23b769;
    border: 1px solid #23b769;
  }
  .el-button--primary:focus,
  .el-button--primary:hover {
    background: #23b769;
    color: #ffffff;
  }
  .el-dialog__footer {
    text-align: center;
  }
}
</style>
